package me.tuyou.activiti;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.task.Task;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.util.FileCopyUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class HelloWorld extends Base {

    //部署流程
    @Test
    public void a_deployProcess() {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder builder = repositoryService.createDeployment();
        builder.addClasspathResource("HelloWorld.bpmn");//bpmn文件的名称
        Deployment deploy = builder.deploy();
        System.out.println(deploy.getId());
    }

    //启动流程
    @Test
    public void b_startProcess() {
        RuntimeService runtimeService = processEngine.getRuntimeService();
        runtimeService.startProcessInstanceByKey("leave");//流程的名称，也可以使用ByID来启动流程
    }

    //查询任务
    @Test
    public void c_queryTask() {
        TaskService taskService = processEngine.getTaskService();
        //根据assignee(代理人)查询任务
        String assignee = "student";
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(assignee).list();

        //首次运行的时候这个没有输出，因为第一次运行的时候扫描act_ru_task的表里面是空的，但第一次运行完成之后里面会添加一条记录，之后每次运行里面都会添加一条记录
        for (Task task : tasks) {
            System.out.println("taskId:" + task.getId() +
                    ",taskName:" + task.getName() +
                    ",assignee:" + task.getAssignee() +
                    ",createTime:" + task.getCreateTime());
        }
    }

    //完成任务
    @Test
    public void d_completeTask() {
        TaskService taskService = processEngine.getTaskService();
        List<Task> studentTaskList = taskService.createTaskQuery().taskAssignee("student").list();
        for (Task task : studentTaskList) {
            taskService.complete(task.getId());
        }
    }

    //流程进度图片展示
    @Test
    public void e_displayPic() throws IOException {
        String deployId = "15001";
        RepositoryService repositoryService = processEngine.getRepositoryService();
        List<String> deploymentResourceNames = repositoryService.getDeploymentResourceNames(deployId);
        String pngStr = null;
        for (String deploymentResourceName : deploymentResourceNames) {
            if (deploymentResourceName.endsWith("png")) {
                pngStr = deploymentResourceName;
            }
        }
        InputStream in = repositoryService.getResourceAsStream(deployId, pngStr);
        OutputStream out = new FileOutputStream("processProgress.png");
        FileCopyUtils.copy(in, out);
    }
}